﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityComponentSystem.Framework;
using EntityComponentSystem.Demos.SpaceAttack.Components;
using EntityComponentSystem.Framework.Math;

namespace EntityComponentSystem.Demos.SpaceAttack.Systems
{
    public class MovementMapper : ComponentMapper
    {
        public PositionComponent Position { get; private set; }
        public VelocityComponent Velocity { get; private set; }

        protected override void OnInit()
        {
            Position = Entity.GetComponent<PositionComponent>();
            Velocity = Entity.GetComponent<VelocityComponent>();
        }
    }

    public interface IMovementSystem : ISystemProcessor
    {

    }

    public class MovementSystem : System<MovementMapper>, IMovementSystem
    {
        public MovementSystem(GameEngine ge)
            : base(ge)
        {

        }

        protected override void OnUpdate(long timeDelta, float timeDeltaF)
        {
            foreach (var am in AllComponentMaps)
            {
                if (am.Velocity.Value != Vector2.Zero)
                {
                    var newPosition = am.Position.Value + am.Velocity.Value * timeDeltaF;

                    if (newPosition.x < 0) newPosition.x = 0;
                    if (newPosition.x > 79) newPosition.x = 79;
                    if (newPosition.y < 0) newPosition.y = 0;
                    if (newPosition.y > 59) newPosition.y = 59;

                    am.Position.Set(newPosition);
                }
            }
        }

        //protected override void OnAddEntity(Entity e)
        //{
        //    base.OnAddEntity(e);
        //    e.Subscribe(new EntityEvent<PositionEvent>(onMoveEvent));
        //}

        //protected override void OnRemoveEntity(Entity e)
        //{
        //    base.OnRemoveEntity(e);
        //    e.Unsubscribe(new EntityEvent<PositionEvent>(onMoveEvent));
        //}

        //private void onMoveEvent(Entity entity, PositionEvent e)
        //{
        //    Console.WriteLine(e.Position.Value);
        //    Console.SetCursorPosition(0, 0);
        //}
    }
}
